package org.example.springcache2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StatusService {
    @Autowired
    StatusRepository statusRepository;
//    根据id获取微博
    @Cacheable(value = "ststus")
    public Status getStatus(int id) {
        return statusRepository.findById(id).orElseThrow();
    }
//    获取某作者的微博条数
    @Cacheable(value = "countStatus", key = "#author.toLowerCase()")
    public int countStatus(String author){
        return statusRepository.findByAuthorIgnoreCase(author).size();
    }

//    获取点赞高于某值的微博
    @Cacheable(value = "hotStatus",condition = "#likes >= 10",unless = "#result.size() == 0")
    public List<Status> getHotStatus(int likes){
        return statusRepository.findByLikesGreaterThan(likes);
    }

//    更新微博
    @CachePut(value = "status",key = "#status.id")
    public void updateStatus(Status status) {
        statusRepository.save(status);
    }
//    清除热门微博缓存
    @CacheEvict(value = "hotStatus",allEntries = true)
    public void evictHotStatus() {

    }
//    删除微博，清除相关缓存
    @Caching(
            evict = {
                    @CacheEvict(value = "status",key = "#id"),
                    @CacheEvict(value = "countStatus",allEntries = true),
                    @CacheEvict(value = "hotStatus",allEntries = true)
            }
    )
    public void removeStatus(int id) {
        statusRepository.deleteById(id);
    }
}
